package cn.lingyangwl.framework.ip2region.handler;

import cn.lingyangwl.framework.ip2region.model.AddressInfo;
import com.maxmind.geoip2.DatabaseReader;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;

/**
 * @author shenguangyang
 */
public class Geoip2Handler implements Ip2RegionOfflineHandler {
    private final String ip;

    private final DatabaseReader reader;

    public Geoip2Handler(String ip, DatabaseReader reader) {
        this.ip = ip;
        this.reader = reader;
    }

    /**
     * 获得国家
     */
    @Override
    public String getCountry() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return "";
        }
        return reader.city(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN");
    }

    /**
     * 获得省份
     */
    @Override
    public String getProvince() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return "";
        }
        return reader.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
    }

    /**
     * 获得城市
     */
    @Override
    public String getCity() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return "";
        }
        return reader.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN");
    }

    /**
     * 获得详细地址
     */
    @Override
    public AddressInfo getAddress() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return new AddressInfo();
        }
        InetAddress inetAddress = InetAddress.getByName(ip);
        String country = reader.city(inetAddress).getCountry().getNames().get("zh-CN");
        String province = reader.city(inetAddress).getMostSpecificSubdivision().getNames().get("zh-CN");
        String city = reader.city(inetAddress).getCity().getNames().get("zh-CN");
        return AddressInfo.builder().city(city).province(province).country(country).build();
    }

    /**
     * 获得经度
     */
    @Override
    public Double getLongitude() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return null;
        }
        return reader.city(InetAddress.getByName(ip)).getLocation().getLongitude();
    }

    /**
     * 获得纬度
     */
    @Override
    public Double getLatitude() throws Exception {
        if (StringUtils.isEmpty(this.ip)) {
            return null;
        }
        return reader.city(InetAddress.getByName(ip)).getLocation().getLatitude();
    }
}
